<?php

namespace app\index\controller;

use app\common\model\jooj_member\MemberIndexInfo as MemberIndexInfoModel;
use app\common\model\jooj_member\MemberIndex as MemberIndexModel;
use app\common\model\jooj_member\MemberTags as MemberTagsModel;
use app\common\model\jooj_member\Tags as TagsModel;
use app\index\service\MemberService;
use app\common\model\oms\MemberSign as MemberSignModel;
use app\common\model\jooj_member\MemberVip as MemberVipModel;
use app\common\model\jooj_member\ViewMemberIndex as ViewMemberIndexModel;
use app\common\model\jooj_member\VipsAddress as VipsAddressModel;
use app\common\model\oms\MemberScanBind as MemberScanBindModel;
use app\common\model\jooj_member\FamilysTies as FamilysTiesModel;
use app\common\service\arvato\ArvatoMemberService;
use app\common\model\jooj_member\Member as MemberModel;
use app\common\model\jooj_member\MemberInfo as MemberInfoModel;
use app\common\service\MemberGetwayService;
use app\common\common\Helper;
use think\Validate;
use app\common\model\oms\Companies as CompaniesModel;
use app\common\arvato\CommonPush as CommonPushModel;
use app\common\model\oms\Staffs as StaffsModel;
use app\common\model\jsm\Mps as MpsModel;

class Member extends \app\common\controller\AuthBase {

    public function __construct() {
        parent::__construct();
    }

    /**
     * 微信账号保存（含注册和编辑）
     * 仅支持memberIndex和memberInfo
     */
    public function wxMemberSave() {
        $param_list = [
            'companyCode' => 'string',
            'openId' => 'string',
        ];
        $params = $this->input();
        //过滤所需参数是存在
        $this->diffParam($param_list, $params);
        $company_id = $this->getCompanyIdByCompanyCode($params['companyCode']);

        $params['company_code'] = $params['companyCode'];
        $params['account_code'] = $params['openId'];
        $params['company_id'] = $company_id;

        try {
            //控制不允许修改的字段
            unset($params['companyCode'], $params['openId'], $params['cardno'], $params['vip_id']);
            $MemberGetwayService = new MemberGetwayService();
            $res = $MemberGetwayService->updateMemberInfo($params, 'OPENID');
            return $this->output($res['data']);
        } catch (\Exception $ex) {
            return $this->output([], $ex->getMessage(), 200);
        }
    }

    /**
     * 微信小程序保存用户信息接口
     */
    public function wxAppMemberSave() {
        $params = $this->input();
        $rule = [
            "company_code" => 'require',
            "union_id" => 'require',
        ];

        $validate = new Validate($rule);
        if (!$validate->check($params)) {
            return $this->output([], $validate->getError());
        }
        $company_id = $this->getCompanyIdByCompanyCode($params['company_code']);

        $params['wx_union_id'] = $params['union_id'];
        isset($params['open_id']) ? $params['account_code'] = $params['open_id'] : '';
        $params['company_id'] = $company_id;
        try {
            //控制不允许修改的字段
            unset($params['cardno'], $params['vip_id']);
            $MemberGetwayService = new MemberGetwayService();
            $res = $MemberGetwayService->updateMemberInfo($params, 'WXUNIONID');
            return $this->output($res['data']);
        } catch (\Exception $ex) {
            return $this->output([], $ex->getMessage(), 200);
        }
    }

    /**
     * acrm同步数据
     * 仅支持memberIndex和memberInfo
     */
    public function saveMemberByCardNo() {
        $param_list = [
            'companyCode' => 'string',
            'card_no' => 'string',
        ];
        $params = $this->input();
        //过滤所需参数是存在
        $this->diffParam($param_list, $params);

        $company_id = $this->getCompanyIdByCompanyCode($params['companyCode']);

        $memberIndexModel = new MemberIndexModel($company_id);
        $memberIndexInfoModel = new MemberIndexInfoModel($company_id);
        $memberVipModel = new MemberVipModel($company_id);

        $openId = isset($params['openid']) ? $params['openid'] : '';
        $mobile = isset($params['mobile']) ? $params['mobile'] : '';
        $params['company_code'] = $params['companyCode'];

        unset($params['openid']);
        (isset($openId) && $openId == '') ? $params['account_code'] = null : $params['account_code'] = $openId;

        try {
            $memberIndex = $memberIndexModel->getMemberIndexByAcrm($params['card_no'], $openId, $mobile);
        } catch (\Exception $ex) {
            return $this->output([], $ex->getMessage());
        }

        $MemberGetwayService = new MemberGetwayService();
        if (empty($memberIndex)) {

            if ($mobile) {
                //手机号码存在就是认证手机号
                $params['mobile_status'] = 1;
            }

            $params['cardno'] = $params['card_no'];
            unset($params['card_no']);

            try {
                $res = $MemberGetwayService->registerMemberInfo($params, $company_id);
                return $this->output($res);
            } catch (\Exception $ex) {
                return $this->output([], $ex->getMessage());
            }
        }

        //修改会员数据
        //判断jj_uni_id是否存在
        $jj_uni_id = $memberIndex['jj_uni_id'];
        if (empty($jj_uni_id)) {
            return $this->output([], 'the member jj_uni_id is empty', 200);
        }

        $memberCodeArr = $memberIndexModel->getMemberCodeArrByUniId($jj_uni_id);
        $memberService = new MemberService();
        //更新数据库的对应字段(避免修改权限过大，如果后期需要扩大修改权限，可以从unset remove)
        unset($params['vip_id']);

        $memberIndexModel->startTrans();

        //如果有，并且openid不存在(强制解绑)

        $memberService->updateMemberFieldByCardNo($company_id, $params, $memberCodeArr, $params['card_no']);
        $memberIndexModel->commit();

//        //重新注册一个粉丝信息推送给arvato
//        $MpsModel = new Mps();
//        $MpsInfo = $MpsModel->getMpsInfoByCondition(['o_id'=>$company_id]);
//        if(empty($MpsInfo)){
//            return $this->output([], "mps信息找不到[companyid=$company_id]");
//        }
//        $res = $MemberGetwayService->addFansInfo($MpsInfo['mp_id'],$memberIndex['account_code'], $company_id);

        return $this->output(['action' => 'update']);
    }

    /**
     * 微信绑定手机号,成为会员
     */
    public function wxBingVipMember() {
        $param_list = [
            'companyCode' => 'string',
            'openId' => 'string',
            'mobile' => 'mobile',
            'Info' => 'array'
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);

        $companyCode = $params['companyCode'];
        $Info = $params['Info'];

        $company_id = $this->getCompanyIdByCompanyCode($params['companyCode']);
        //验证手机号是否可以绑定了
        $MemberService = new MemberService();
        $result = $MemberService->mobileCanBind($company_id, $params['mobile']);

        if ($result === false) {
            return $this->output([], 'the mobile already have account_code');
        }
        //检验各个企业不同的规则（以便于后面统一处理逻辑）
        $this->checkMemberRules($companyCode, $Info, $company_id, $params['mobile']);

        $viewMemberIndexModel = new ViewMemberIndexModel($company_id);
        $memberIndexModel = new MemberIndexModel($company_id);
        $memberIndexInfoModel = new MemberIndexInfoModel($company_id);
        $memberVipModel = new MemberVipModel($company_id);

        $viewMemberIndexModel->startTrans();
        //1、通过openId判断是不是粉丝(1)不是粉丝不能绑定成为会员(2)已经是会员了不能成为会员
        $viewMemberIndex_openId = $viewMemberIndexModel->getViewMemberIndexByCondition(['account_code' => $params['openId']]);
        if (empty($viewMemberIndex_openId)) {
            return $this->output([], 'Sorry, you are not a fans yet');
        }
        if (!empty($viewMemberIndex_openId['vip_id'])) {
            return $this->output([], 'Sorry, you are already a VIP user');
        }

        //2、通过手机号取判断（1）手机号已经注册了,并且绑定了微信，不可以再注册成为会员(上checkMemberRules处理)
        $viewMemberIndex_mobile = $viewMemberIndexModel->getViewMemberIndexByCondition(['mobile' => $params['mobile'], 'mobile_status' => 1]);
        $memberCodeArr = [];
        $memberCodeArr[] = $viewMemberIndex_openId['member_code'];

        /*         * 以上就是验证全部通过，基于以下情况绑定数据* */
        switch (true) {
            //绑定1，有mobile没有认证记录的情况，把mobile绑定到openId上
            //因为所有业务都是以微信的openId为核心点，所以说，可能之前就有潜客绑定微信的情况
            //为了保证数据的完整性，会把手机号的uni_id更新为和微信一样的
            case!empty($viewMemberIndex_mobile):
                $memberCode = $viewMemberIndex_mobile['member_code'];
                $uniId_openId = $viewMemberIndex_openId['jj_uni_id'];
                $memberCodeArr = $memberIndexModel->bindMemberIndex('mutil', 0, 0, $memberCode, $uniId_openId);
                if (empty($memberCodeArr)) {
                    return $this->output([], 'Sorry,memberIndex update fail');
                }
                $memberIndexInfoModel->clearBindData($memberCodeArr);
                break;
            //绑定2，没有mobile记录，最简单，把手机号给绑定到openId的记录上即可
            case empty($viewMemberIndex_mobile):
                $res = $memberIndexModel->bindMemberIndex('mobile', $params['mobile'], $params['openId'], 0, 0);
                if (!$res) {
                    return $this->output([], 'Sorry,memberIndex update fail');
                }
                break;
            default :
                break;
        }

        /** 绑定完毕，这时候看vip表里是否有数据* */
        if (empty($viewMemberIndex_mobile) || $viewMemberIndex_mobile['mobile_status'] == 2) {
            //注册
            $newViewMemberIndex = $viewMemberIndexModel->getViewMemberIndexByCondition(['mobile' => $params['mobile']]);
            //新的view里面所有的数据都是新的了，包括first_p,service_p等相关参数
            /*
              $memberService = new MemberGetwayService();
              $CardInfo = $memberService->createCardNo($newViewMemberIndex['jj_uni_id'], $params['companyCode']);
              if (!isset($CardInfo['cardno'])) {
              return $this->output([], 'card no create fail');
              }
             * 
             */
            $data = [
                'member_code' => current(explode(',', $viewMemberIndex_openId['member_code'])),
                'cardno' => $newViewMemberIndex['cardno'],
                'card_lev' => $newViewMemberIndex['card_lev'],
                'mobile' => $newViewMemberIndex['mobile'] ?: $params['mobile'],
                'name' => $newViewMemberIndex['name'],
                'gender' => $newViewMemberIndex['gender'],
                'birthday' => $newViewMemberIndex['birthday'],
                'first_p' => $newViewMemberIndex['first_p'],
                'first_store' => $newViewMemberIndex['first_store'],
                'first_qrscene' => $newViewMemberIndex['first_qrscene'],
            ];

            $id = $memberVipModel->addMemberVip($data);
            $addData = [
                'vip_id' => $id,
                'mobile_status' => 1
            ];
            $Info = array_merge($addData, $Info);
        }
        //更新数据
        $memberService = new MemberGetwayService();
        $memberService->updateViewField($company_id, $Info, $memberCodeArr, $params['openId']);

        $viewMemberIndexModel->commit();

        $arvatoMemberService = new ArvatoMemberService();
        if (empty($viewMemberIndex_mobile) || $viewMemberIndex_mobile['mobile_status'] == 2) {
            //同步推送arvato，获取card_lev
            $res = $arvatoMemberService->updateMemberInfo_sync($newViewMemberIndex['jj_uni_id'], $params['companyCode']);

            if (isset($res)) {
                $Info = ['card_lev' => $res['card_level']];
                $memberService->updateViewField($company_id, $Info, $memberCodeArr);
            } else {
                return $this->output([], 'card_level update fail');
            }
        } else {
            //将数据推送给arvato
            $newCardLev = $arvatoMemberService->bindOpenid($params['openId'], $params['companyCode']);
            if ($newCardLev != '') {
                $memberService->updateViewField($company_id, ['card_lev' => $newCardLev], $memberCodeArr, $params['openId']);
            }
        }


        return $this->output(['action' => 'update']);
    }

    /**
     * 为了避免出现多个像宝岛一样，对于会员有特殊定义的需求，影响业务
     * 故设定一个统一的判断入口，将逻辑理清
     */
    private function checkMemberRules($companyCode, $info, $company_id, $mobile) {

        switch ($companyCode) {
            case 'baodao':
                //判断四项基本资料是否完善
                if (empty($info['name']) || empty($info['gender']) || empty($info['birthday'])) {
                    return $this->output([], 'the four basic data are not perfect');
                }
                break;
            default:
                $viewMemberIndexModel = new ViewMemberIndexModel($company_id);
                //2、通过手机号取判断（1）手机号已经注册了,并且绑定了微信，不可以再注册成为会员
                $viewMemberIndex_mobile = $viewMemberIndexModel->getViewMemberIndexByCondition(['mobile' => $mobile, 'mobile_status' => 1]);
                if (!empty($viewMemberIndex_mobile) && $viewMemberIndex_mobile['account_code']) {
                    return $this->output([], 'Sorry, the mobile has already bind other open_id');
                }
                break;
        }

        return true;
    }

    /**
     * 通过微信的openid获取账号信息(建议作废，因为相关信息只能走视图)
     */
    public function getMemberIndexVipInfoByOpenId() {
        $param_list = [
            'companyCode' => "string",
            'openId' => 'string',
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);

        $company_id = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $viewMemberIndexModel = new ViewMemberIndexModel($company_id);

        $type = isset($params['type']) ? $params['type'] : 'simple';

        $memberIndex = $viewMemberIndexModel->getViewMemberIndexByCondition($params['openId']);

        if ($type == 'simple') {
            return $this->output($memberIndex);
        }

        if (!isset($memberIndex['vip_id']) || $memberIndex['vip_id'] <= 0) {
            $memberIndex['vip_info'] = null;
            return $this->output($memberIndex);
        }

        $vipId = $memberIndex['vip_id'];
        $memberVipModel = new MemberVipModel($company_id);
        $memberVip = $memberVipModel->getMemberVipByVipId($vipId);

        $memberIndex['vip_info'] = $memberVip;

        return $this->output($memberIndex);
    }

    /**
     * 通过手机号获取member信息
     */
    public function getMemberViewByMobile() {
        $param_list = [
            'companyCode' => 'string',
            'mobile' => 'mobile'
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);

        $company_id = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $viewMemberIndexModel = new ViewMemberIndexModel($company_id);

        $where = ['mobile' => $params['mobile']];

        $where['mobile_status'] = isset($params['mobile_status']) ? $params['mobile_status'] : 1;

        $viewMemberIndex = $viewMemberIndexModel->getViewMemberIndexByCondition($where);

        return $this->output($viewMemberIndex);
    }

    /**
     * 通过手机号获取member信息
     */
    public function getMemberViewByOpenId() {
        $param_list = [
            'companyCode' => 'string',
            'openId' => 'string'
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);

        $company_id = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $viewMemberIndexModel = new ViewMemberIndexModel($company_id);

        $viewMemberIndex = $viewMemberIndexModel->getViewMemberIndexByCondition(['account_code' => $params['openId']]);

        return $this->output($viewMemberIndex);
    }

    /**
     * 通过手机号获取member信息
     */
    public function getMemberViewByCardNo() {
        $param_list = [
            'companyCode' => 'string',
            'cardno' => 'string'
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);

        $company_id = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $viewMemberIndexModel = new ViewMemberIndexModel($company_id);

        $viewMemberIndex = $viewMemberIndexModel->getViewMemberIndexByCondition(['cardno' => $params['cardno']]);

        return $this->output($viewMemberIndex);
    }

    /**
     * 更新vip的信息
     * @return type
     * @deprecated since leo.xie newMember 走统一的方法
     */
    public function updateVipInfoByVipId() {
        $param_list = [
            'companyCode' => 'string',
            'vipId' => 'number'
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);

        $company_id = $this->getCompanyIdByCompanyCode($params['companyCode']);

        $memberIndexModel = new MemberIndexModel($company_id);
        $memberVipModel = new MemberVipModel($company_id);

        $count = 0;
        $updateVip = $memberVipModel->updateMemberVipByVipId($params['vipId'], $params);
        if ($updateVip) {
            $count++;
        }

        $updateIndex = $memberIndexModel->updateMemberIndexSyncVip($params['vipId'], $params);
        if ($updateIndex) {
            $count++;
        }
        return $this->output(['row' => $count]);
    }

    /**
     * 通过条件获取memberVip列表
     * @return type json
     */
    public function searchMemberVips() {
        $param_list = [
            'companyCode' => 'string',
            'page' => 'number',
            'pageSize' => 'number',
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);

        $company_id = $this->getCompanyIdByCompanyCode($params['companyCode']);

        $where = [];
        //可选条件
        if (isset($params['gender']) && $params['gender'] < 3) {
            $where['gender'] = $params['gender'];
        }
        if (isset($params['province'])) {
            $where['province'] = $params['province'];
        }
        if (isset($params['city'])) {
            $where['city'] = $params['city'];
        }
        if (isset($params['cardno'])) {
            $where['cardno'] = $params['cardno'];
        }
        if (isset($params['name'])) {
            $where['name'] = $params['name'];
        }
        if (isset($params['mobile'])) {
            $where['mobile'] = $params['mobile'];
        }

        switch (true) {
            case!empty($params['date_start']) && empty($params['date_end']):
                $date_start = strtotime($params['date_start'] . ' 00:00:00');
                $where['add_ts'] = ['egt', $date_start];
                break;
            case empty($params['date_start']) && !empty($params['date_end']):
                $date_end = strtotime($params['date_end'] . ' 23:59:59');
                $where['add_ts'] = ['elt', $date_end];
                break;
            case!empty($params['date_start']) && !empty($params['date_end']):
                $date_start = strtotime($params['date_start'] . ' 00:00:00');
                $date_end = strtotime($params['date_end'] . ' 23:59:59');
                $where['add_ts'] = ['between', [$date_start, $date_end]];
                break;
            default :
                break;
        }

        $where = array_filter($where);

        $MemberVipModel = new MemberVipModel($company_id);
        $list = $MemberVipModel->getPage($params['page'], $params['pageSize'], $where);

        return $this->output($list);
    }

    /**
     * 通过手机号获取vip表的信息
     * 不可以只获取会员数据，要通过视图，所以作废
     */
    public function getMemberVipByMobile() {
        $param_list = [
            'mobile' => 'mobile',
            'companyCode' => 'string',
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);

        $company_id = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $viewMemberIndexModel = new ViewMemberIndexModel($company_id);

        $viewMemberIndex = $viewMemberIndexModel->getViewMemberIndexByCondition(['mobile' => $params['mobile']]);

        return $this->output($viewMemberIndex);
    }

    /**
     * 获取公司下的用户标签
     */
    public function getTagsByCompany() {
        $param_list = [
            'companyCode' => 'string',
            'memberCode' => 'string',
        ];
        $params = $this->input();
        //过滤所需参数是否存在
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        //通过memberCode或者vipId获取memberCode数组
        $memberIndexModel = new MemberIndexModel($companyId);
        $memberCodeArr = $memberIndexModel->getMemberCodeArrByMemberCode($params['memberCode']);
        if (empty($memberCodeArr)) {
            return $this->output([], 'memberCode is error', 200);
        }
        //基于memberCode的数组去查找会员标签
        $memberTagsModel = new MemberTagsModel($companyId);
        $memberTags = $memberTagsModel->getTags($memberCodeArr);
        $memberTags = array_values($memberTags);

        return $this->output($memberTags);
    }

    /**
     * 给会员新增标签
     */
    public function addTagByCompany() {
        $param_list = [
            'companyCode' => 'string',
            'memberCode' => 'string',
            'tagIds' => 'string', //字符串拆分
            'staffId' => 'string',
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $company_id = $this->getCompanyIdByCompanyCode($params['companyCode']);
        //通过memberCode或者vipId获取memberCode数组
        $memberIndexModel = new MemberIndexModel($company_id);
        $memberCodeArr = $memberIndexModel->getMemberCodeArrByMemberCode($params['memberCode']);
        if (empty($memberCodeArr)) {
            return $this->output([], 'memberCode is error', 200);
        }
        //基于memberCode的数组去查找会员标签
        $memberTagsModel = new MemberTagsModel($company_id);
        $memberTags = $memberTagsModel->addTags($memberCodeArr, $params['memberCode'], $params['tagIds']);
        if ($memberTags === false) {
            return $this->output([], 'tagsId is error', 200);
        }
        //通知arvato
        $viewMemberModel = new ViewMemberIndexModel($company_id);
        $memberInfoData = $viewMemberModel->getViewMemberIndexByCondition(['member_code' => $params['memberCode']]);
        $commonPush = new CommonPushModel();
        $staffModel = new StaffsModel();
        $service = new MemberService();
        $tagValueArr = $service->getTagValueArrayByTagIdString($params['tagIds'], $company_id);
        $pushData = [
            'card_no' => $memberInfoData['cardno'],
            'tag_value' => $tagValueArr,
            'emp_code' => $staffModel->where(['staff_id' => $params['staffId']])->value('staff_job_id')
        ];
        $commonPush->pushToRedis($pushData, 'addImpression');
        return $this->output($memberTags);
    }

    /**
     * 获取这个公司下的标签列表
     */
    public function getTagsPage() {
        $param_list = [
            'companyCode' => 'string',
            'page' => 'number',
            'pageSize' => 'number',
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);

        $company_id = $this->getCompanyIdByCompanyCode($params['companyCode']);

        $tagModel = new TagsModel($company_id);
        $tag = $tagModel->getTagsPage($params['page'], $params['pageSize'], []);

        return $this->output($tag);
    }

    /**
     * 获取到店列表
     * @return type json
     */
    public function getVisitingMember() {

        $param_list = [
            'serviceStore' => 'string',
            'companyCode' => 'string'
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $memberSignModel = new MemberSignModel($companyId);
        $memberSignList = $memberSignModel->getMemberSignList($params['serviceStore'], $params);
        return $this->output($memberSignList);
    }

    /**
     * 判断手机号是否可以绑定
     * @deprecated since version 新会员系统
     */
    public function checkMobileNoCanBind() {
        $param_list = [
            'companyCode' => 'string',
            'mobile' => 'mobile',
        ];

        $params = $this->input();
        $this->diffParam($param_list, $params);

        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);

        $MemberService = new MemberService();
        $result = $MemberService->mobileCanBind($companyId, $params['mobile']);

        if ($result === false) {
            return $this->output([], 'the mobile already have account_code');
        }

        return $this->output();
    }

    /**
     * 会员签到
     * @return type json
     */
    public function memberCheckin() {
        $param_list = [
            'serviceP' => 'string',
            'companyCode' => 'string',
            'memberCode' => 'string',
            'serviceStore' => 'string'
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $memberSignModel = new MemberSignModel($companyId);

        $params = Helper::toUnderScore($params);
        $memberCheckIn = $memberSignModel->memberCheckin($params, $params['company_code']);
        if (empty($memberCheckIn)) {
            return $this->output([], '签到失败', 200);
        }
        return $this->output($memberCheckIn, $msg = 'success', 200);
    }

    /**
     * 注册会员
     * @return type json
     */
    public function memberRegister() {

        $param_list = [
            'companyCode' => 'string',
//            'name' => 'string',
//            'birthday' => 'string',
            'comeFrom' => 'string',
        ];

        $params = $this->input();
        $this->diffParam($param_list, $params);
        $params['gender'] = $params['gender'] ? $params['gender'] : 0;
        $params['mobileStatus'] = $params['mobileStatus'] ? $params['mobileStatus'] : 2;
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);

        try {
            $params = Helper::toUnderScore($params);
            $MemberGetwayService = new MemberGetwayService();
            $res = $MemberGetwayService->registerMemberInfo($params, $companyId);
            return $this->output($res['data']);
        } catch (\Exception $ex) {
            return $this->output([], $ex->getMessage());
        }
    }

    /**
     * 编辑会员信息
     * @return type json
     */
    public function editMemberInfo() {
        $param_list = [
            'memberCode' => 'string',
            'companyCode' => 'string'
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);

        try {
            $params = Helper::toUnderScore($params);
            $params['company_id'] = $companyId;
            $MemberGetwayService = new MemberGetwayService();
            $res = $MemberGetwayService->updateMemberInfo($params, 'MEMBERCODE');
            return $this->output($res);
        } catch (\Exception $ex) {
            return $this->output([], $ex->getMessage());
        }
    }

    /**
     * 获取memberCode
     * @return type json
     * @deprecated since version 走视图逻辑
     */
    public function getMemberInfoByMemberCode() {
        $param_list = [
            'memberCode' => 'string',
            'companyCode' => 'string'
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $memberModel = new ViewMemberIndexModel($companyId);
        $where['member_code'] = $params['memberCode'];
        $data = $memberModel->getViewInfoByCondition($where);
        if (empty($data)) {
            return $this->output([], "don't have record", 200);
        }
        return $this->output(array_values($data));
    }

    /**
     * 通过wx_union_id
     */
    public function getMemberInfoByWxUnionId() {
        $param_list = [
            'union_id' => 'string',
            'company_code' => 'string'
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['company_code']);
        $memberModel = new ViewMemberIndexModel($companyId);
        $where['wx_union_id'] = $params['union_id'];
        $data = $memberModel->getViewMemberIndexByCondition($where);
        if (empty($data)) {
            return $this->output([], "don't have record", 200);
        }
        return $this->output($data);
    }

    /**
     * 更新会员信息
     * @return type json
     */
    public function updateMemberInfo() {
        $param_list = [
            'memberCode' => 'string',
            'companyCode' => 'string'
        ];
        // 验证入参
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        try {
            $params = Helper::toUnderScore($params);
            $params['company_id'] = $companyId;
            $MemberGetwayService = new MemberGetwayService();
            $res = $MemberGetwayService->updateMemberInfo($params, 'MEMBERCODE');
            if (isset($res['data'])) {
                return $this->output($res['data']);
            }

            return $this->output($res);
        } catch (\Exception $ex) {
            return $this->output([], $ex->getMessage());
        }
    }

    /**
     * 获取地址列表
     * @return type json
     */
    public function memberAddressList() {
        $param_list = [
            'memberCode' => 'string',
            'companyCode' => 'string'
        ];
        // 验证入参
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $page = $params['page'] ? $params['page'] : 1;
        $pageSize = $params['pageSize'] ? $params['pageSize'] : 10;
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $vipAddressModel = new VipsAddressModel($companyId);
        $list = $vipAddressModel->getVipAddressList(['member_code' => $params['memberCode']], $page, $pageSize);
        return $this->output($list);
    }

    /**
     * 增加一条地址
     * @return type json
     */
    public function addMemberAddress() {
        $param_list = [
            'memberCode' => 'string',
            'companyCode' => 'string',
            'provinceName' => 'string',
            'cityName' => 'string',
            'address' => 'string',
            'receiveName' => 'string',
            'mobile' => 'string',
        ];
        // 验证入参
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $vipAddressModel = new VipsAddressModel($companyId);
        unset($params['companyCode']); //数据库里没此字段
        $params['vip_id'] = $params['memberCode'];
        $add = $vipAddressModel->addMemberAddress($params);
        if (false === $add) {
            return $this->output([], '插入数据库失败', 200);
        }
        return $this->output($add);
    }

    /**
     * 更新一条地址
     * @return type json
     */
    public function updateMemberAddress() {
        $param_list = [
            'id' => 'string',
            'memberCode' => 'string',
            'companyCode' => 'string',
            'provinceName' => 'string',
            'cityName' => 'string',
            'address' => 'string',
            'receiveName' => 'string',
            'mobile' => 'string',
        ];
        // 验证入参
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $vipAddressModel = new VipsAddressModel($companyId);
        unset($params['companyCode']); //数据库里没此字段
        $params['vip_id'] = $params['memberCode'];
        $where['id'] = $params['id'];
        unset($params['id']);
        $update = $vipAddressModel->updateMemberAddress($where, $params);
        if (false === $update) {
            return $this->output([], '更新数据库失败', 200);
        }
        return $this->output($update);
    }

    public function delOneAddress() {
        $param_list = [
            'id' => 'string',
            'companyCode' => 'string'
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $vipAddressModel = new VipsAddressModel($companyId);
        $delAddressOne = $vipAddressModel->delOneById($params['id']);
        if (false === $delAddressOne) {
            return $this->output([], '更新数据库失败', 200);
        }
        return $this->output($delAddressOne);
    }

    /**
     * 获取会员列表
     * @return type json
     */
    public function getMemberList() {
        $param_list = [
            'keyword' => 'string',
            'companyCode' => 'string'
        ];
        // 验证入参
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $memberService = new MemberService();
        $memberList = $memberService->getMemberListByKeyword($params['keyword'], $companyId, $params['page'], $params['pageSize']);
        if (false === $memberList) {
            return $this->output([], '获取内容为空', 200);
        }
        return $this->output($memberList);
    }

    /**
     * 验证是否满足发送条件
     * @return type json
     */
    public function memberSendNoticeValidate() {
        $param_list = [
            'mobile' => 'string',
            'companyCode' => 'string',
            //      'expirMinute' => 'string', //验证码有效期
            'type' => 'string', //（1注册 2绑定）
                //      'codeType'    => 'string'//指定短信还是语音
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $memberService = new MemberService();
        $sendStatus = $memberService->memberSendNoticeValidate($params, $companyId);
        if ('success' === $sendStatus['desc']) {
            return $this->output([]);
        }
        return $this->output($sendStatus['data'], $sendStatus['desc']);
    }

    /**
     * @Title  : 查询该会员扫码是否成功
     * @Param  : post 【int】logId(日志表自增ID)
     * @Return : json
     * @Autor  : 作者（tommy.pan）
     * @Date   : 开发时间（2017-6-27） 
     */
    public function LogIdScan() {
        //post搜集参数
        $param_list = [
            'logId' => 'string',
            'companyCode' => 'string'
        ];
        // 验证入参
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $memberScanBind = new MemberScanBindModel($companyId);
        $result = $memberScanBind->findResultByCondition(['usb_id' => $params['logId']], $field = 'status ,message');
        $res = explode('，', $result['message']);
        $data['message'] = $res[0];
        $data['status'] = (string) $result['status'];
        return $this->output($data);
    }

    /**
     * @Title  : 获得临时二维码地址
     * @Param  : post 【string】vipId(会员ID)|【int】serviceP（验光师ID）|【int】serviceStore(门店ID)
     * @Return : json
     * @Autor  : 作者（tommy.pan）
     * @Date   : 开发时间（2017-06-24）
     */
    public function getBarcode() {
        //post搜集参数

        $param_list = [
            'logId' => 'string',
            'companyCode' => 'string',
            'serviceP' => 'string',
            'serviceStore' => 'string',
            'memberCode' => 'string'
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $memberService = new MemberService();
        $getBarcode = $memberService->getBarcode($params, $companyId);
        return $this->output($getBarcode);
    }

    public function getMemberInfo() {
        $param_list = [
            'companyCode' => 'string',
            'memberCode' => 'string'
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $condition = ['member_code' => $params['memberCode']];
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $memberService = new MemberService();
        $memberInfo = $memberService->getMemberInfo($params, $companyId);
        return $this->output($memberInfo);
    }

    /**
     *
     * 查询家庭成员
     * @return type
     */
    public function familyMemberInfo() {
        $param_list = [
            'companyCode' => 'string',
            'memberCode' => 'string'
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $memberService = new MemberService();
        $memberFamilys = $memberService->getFamilyInfo($params, $companyId);
        if (empty($memberFamilys)) {
            $memberFamilys = [];
        }
        return $this->output($memberFamilys);
    }

    /**
     * 家庭成员关系绑定
     * @return type json
     */
    public function familyRelationBind() {
        $param_list = [
            'companyCode' => 'string'
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $memberService = new MemberService();
        $familyRelationBind = $memberService->familyRelationBind($params, $companyId);

        if ('success' != $familyRelationBind['msg']) {
            return $this->output([], '家庭成员关系绑定失败,' . $familyRelationBind['msg']);
        }
        return $this->output();
    }

    /**
     * @Title  : 家庭成员关系类型查询
     * @Param  : post 【string】sex(使用者性别要求：0其他；1男；2女)
     * @Return : json
     */
    public function familyRelationList() {
        $param_list = [
            'companyCode' => 'string',
            'gender' => 'int',
            'page' => 'string',
            'pageSize' => 'string'
        ];
        $params = $this->input();
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $familyTiesModel = new FamilysTiesModel($companyId);
        $page = $params['page'] ? $params['page'] : '1';
        $pageSize = $params['pageSize'] ? $params['pageSize'] : '10';
        $where = ['member_gender' => $params['gender']];
        $list = $familyTiesModel->getPageListByCondition($where, $page, $pageSize, '*', 'sort desc');
        if (empty($list)) {
            return $this->output($params = [], $msg = '获取家庭成员关系类型查询失败');
        }
        return $this->output($list);
    }

    /**
     * 开始和结束服务
     * 
     * @author tommy.pan
     * @return json
     */
    public function serviceAction() {
        $params = $this->input();
        $param_list = [
            'companyCode' => 'string',
            'serviceP' => 'string',
            'serviceStore' => 'string',
            'memberCode' => 'string',
        ];
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $memberService = new MemberService();
        $serviceAction = $memberService->serviceAction($params, $companyId);
        if ('success' != $serviceAction['msg']) {
            return $this->output([], $serviceAction['msg']);
        }
        return $this->output($serviceAction['data']);
    }

    /**
     * 删除家庭成员
     * @return type
     */
    public function removeFamily() {
        $params = $this->input();
        $param_list = [
            'companyCode' => 'string',
            'familyId' => 'string',
            'staffId' => 'string',
        ];
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $memberService = new MemberService();
        $remove = $memberService->removeFamily($params, $companyId);
        if (false === $remove) {
            return $this->output([], '移除家庭关系失败');
        }
        return $this->output([]);
    }

    /**
     * 通过wx_union_id 查询 vip_id
     * @return type
     */
    public function getVipIdByUnionId() {
        $params = $this->input();
        $param_list = [
            'company_id' => 'int',
            'union_id' => 'string'
        ];

        $this->diffParam($param_list, $params);
        $member_info_model = new MemberInfoModel($params['company_id']);

        $vip_id = $member_info_model->get_vip_id_by_union_id($params['union_id']);
        return $this->output($vip_id);
    }

    //根据unionid获取宝岛会员体系会员详情
    public function getBaodaoMemberInfoByUnionid() {
        $params = $this->input();

        $param_list = [
            'companyCode' => 'string',
            'unionid' => 'string',
        ];
        $this->diffParam($param_list, $params);

        $MemberModel = new MemberModel;

        $res = $MemberModel->getMemberInfo(['info.wx_unionid' => $params['unionid']]);

        if (false === $res['status']) {
            return $this->outPutError($res);
        }

        return $this->output($res);
    }

    //根据unionid注册宝岛潜客，并返回注册的vipid
    public function registerBaodaoMemberInfoByUnionid() {
        $params = $this->input();

        $param_list = [
            'companyCode' => 'string',
            'unionid' => 'string',
                // 'mobile' => 'int|max:11',
        ];
        $this->diffParam($param_list, $params);

        $MemberModel = new MemberModel;

        $res = $MemberModel->getMemberInfo(['info.wx_unionid' => $params['unionid']]);

        if (false === $res['status']) {
            return $this->outPutError($res);
        }

        //if (empty($res) || (!$res['MobileNO'])) {
        if (empty($res)) {
            try {
                //$res = $MemberModel->registerMember(['wx_unionid' => $params['unionid'], 'mobile' => $params['mobile']]);
                $res = $MemberModel->registerMemberNoMobile(['wx_unionid' => $params['unionid']]);
            } catch (\Exception $e) {
                return $this->outPutError(['msg' => $e->getMessage()]);
            }
        $inPut = file_get_contents("php://input");
        return Helper::outPutError(['msg' => json_encode($data)], $inPut, '');
            return $this->output(['vip_id' => $res]);
        }

        return $this->outPutError(['msg' => 'unionid is existed']);
    }

    /**
     * 查询memberCode数组
     */
    public function getMemberCodeArrByMemberCode() {
        $params = $this->input();
        $param_list = [
            'companyCode' => 'string',
            'memberCode' => 'string',
        ];
        $this->diffParam($param_list, $params);
        $companyId = $this->getCompanyIdByCompanyCode($params['companyCode']);
        $memberIndexModel = new MemberIndexModel($companyId);
        $memberCodeArr = $memberIndexModel->getMemberCodeArrByMemberCode($params['memberCode']);
        if (empty($memberCodeArr)) {
            return $this->output([], 'memberCode is error', 200);
        }
        return $this->output($memberCodeArr);
    }

}
